package io.spring.start.site.extension.dependency.web;

import io.spring.initializr.generator.io.template.MustacheTemplateRenderer;
import io.spring.initializr.generator.language.Language;
import io.spring.initializr.generator.project.ProjectDescription;
import io.spring.initializr.generator.project.contributor.ProjectContributor;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

public class ControllerProjectContributor implements ProjectContributor {

	private final ProjectDescription description;

	private final MustacheTemplateRenderer templateRenderer;

	public ControllerProjectContributor(ProjectDescription description, MustacheTemplateRenderer templateRenderer) {
		this.description = description;
		this.templateRenderer = templateRenderer;
	}

	@Override
	public void contribute(Path projectRoot) throws IOException {
		String groupId = description.getGroupId();
		String artifactId = description.getArtifactId();
		Language language = description.getLanguage();
		String languageId = language.id();
		String sourceFileExtension = language.sourceFileExtension();

		Path configDirectory = projectRoot
			.resolve("src/main/%s/%s/%s/controller".formatted(languageId, groupId.replace(".", "/"), artifactId));
		Files.createDirectories(configDirectory);

		Path myBatisPlusConfig = configDirectory.resolve("TestController.%s".formatted(sourceFileExtension));
		Files.createFile(myBatisPlusConfig);

		Map<String, Object> model = Map.of("packageName", "%s.%s.controller".formatted(groupId, artifactId));
		String templateName = "controller-%s".formatted(languageId);
		String configContent = this.templateRenderer.render(templateName, model);
		Files.write(myBatisPlusConfig, configContent.getBytes());
	}

}
